import { useEffect, useRef, useState, type FC } from "react";

interface UseDeboundsProps {
  value: string
  delay: number
}

const useDebounds: FC<UseDeboundsProps> = ({ value, delay }) => {
  // 一个可以更新的状态值
  const [deBoundsValue, setDeBoundsValue] = useState(value)
  const timerId = useRef<undefined | number>(undefined)

  useEffect(() => {
    // 定时器id
    if (timerId.current) clearTimeout(timerId.current)
    timerId.current = window.setTimeout(() => {
      setDeBoundsValue(value)
      timerId.current = undefined
    }, delay)
  }, [value, delay])

  return deBoundsValue

}

export default useDebounds
